package com.jm.common.conf.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author kong
 */
@Aspect
@Component
public class DataSourceAspect {

    @Pointcut("@annotation(com.jm.common.conf.datasource.DS)")
    public void pointCut() {

    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        DS dataSource = method.getAnnotation(DS.class);
        if (dataSource == null) {
            DynamicDataSource.set("master");
        } else {
            DynamicDataSource.set(dataSource.name());
        }
        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clear();
        }
    }
}